package cn.net.autocode.platform.providers;

import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.platform.datasource.AutoCodeQuery;
import cn.net.autocode.platform.factory.AutoCodeQueryFactory;
import cn.net.autocode.platform.factory.SpringBeanFactory;
import cn.net.autocode.platform.providers.container.DataSourceContainer;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.lang.reflect.Method;
import java.util.Map;

@RestController
@RequestMapping("autocode")
@Slf4j
public class DataSourceProviderCtrl implements ApplicationListener<ApplicationReadyEvent> {


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        Map<String,Object> beans = SpringBeanFactory.getBeansByAnnotation(AutoCodeQuery.class);
        for(Object object:beans.values()){
            AutoCodeQuery beanAnnotation = object.getClass().getAnnotation(AutoCodeQuery.class);
            String dataSource1 = beanAnnotation.value();
            Method[] methods = object.getClass().getMethods();
            for (Method method : methods) {
                AutoCodeQuery methodAnnotation = method.getAnnotation(AutoCodeQuery.class);
                if (methodAnnotation != null) {
                    String dataSource2 = methodAnnotation.value();
                    String key = dataSource1 + "." + dataSource2;
                    if (DataSourceContainer.methodMap.containsKey(key)) {
                        throw new RuntimeException("系统中存在重复定义的数据源【"+key+"】");
                    }
                    DataSourceContainer.methodMap.put(key, method);
                    DataSourceContainer.beanMap.put(key, object);
                }
            }

        }
    }

    @RequestMapping("queryDs/{dataSource}")
    public ResultT queryDs(@PathVariable("dataSource") String dataSource, @RequestBody JSONObject data){
        return AutoCodeQueryFactory.queryDs(dataSource,data);
    }

}
